// 吃饭抽奖应用
class FoodLottery {
    constructor() {
        // 默认菜品列表
        this.defaultFoods = [
            '🍜 拉面', '🍕 披萨', '🍔 汉堡', '🍣 寿司',
            '🍝 意面', '🥗 沙拉', '🍛 咖喱', '🌮 墨西哥卷',
            '🍳 蛋炒饭', '🥟 饺子', '🍲 火锅', '🥘 炖菜'
        ];
        
        // 当前菜品列表
        this.currentFoods = [...this.defaultFoods];
        
        // 转盘颜色
        this.colors = [
            '#FF6B9D', '#FF8E9B', '#FFB3BA', '#FFC0CB',
            '#FFB6C1', '#FFA0AC', '#FF91A4', '#FF7F9A',
            '#FF69B4', '#FF1493', '#DC143C', '#B22222'
        ];
        
        // 转盘状态
        this.isSpinning = false;
        this.currentRotation = 0;
        
        // DOM元素
        this.wheel = document.getElementById('wheel');
        this.spinBtn = document.getElementById('spinBtn');
        this.customFoodInput = document.getElementById('customFood');
        this.addFoodBtn = document.getElementById('addFood');
        this.defaultFoodsContainer = document.getElementById('defaultFoods');
        this.resultSection = document.getElementById('resultSection');
        this.resultFood = document.getElementById('resultFood');
        this.resultTime = document.getElementById('resultTime');
        this.lastResult = document.getElementById('lastResult');
        
        this.init();
    }
    
    init() {
        this.createWheel();
        this.createDefaultFoodTags();
        this.bindEvents();
        this.loadLastResult();
    }
    
    // 创建转盘
    createWheel() {
        this.wheel.innerHTML = '';
        const sectionAngle = 360 / this.currentFoods.length;
        
        // 创建一个完整的SVG转盘
        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('viewBox', '0 0 200 200');
        svg.style.width = '100%';
        svg.style.height = '100%';
        svg.style.position = 'absolute';
        
        this.currentFoods.forEach((food, index) => {
            const startAngle = index * sectionAngle - 90; // -90度让第一个扇形从顶部开始
            const endAngle = (index + 1) * sectionAngle - 90;
            
            // 转换为弧度
            const startRad = (startAngle * Math.PI) / 180;
            const endRad = (endAngle * Math.PI) / 180;
            
            // 计算路径点
            const radius = 90;
            const centerX = 100;
            const centerY = 100;
            
            const x1 = centerX + radius * Math.cos(startRad);
            const y1 = centerY + radius * Math.sin(startRad);
            const x2 = centerX + radius * Math.cos(endRad);
            const y2 = centerY + radius * Math.sin(endRad);
            
            const largeArcFlag = sectionAngle > 180 ? 1 : 0;
            
            // 创建扇形路径
            const pathData = [
                `M ${centerX} ${centerY}`,
                `L ${x1} ${y1}`,
                `A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2}`,
                'Z'
            ].join(' ');
            
            // 创建路径元素
            const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
            path.setAttribute('d', pathData);
            path.setAttribute('fill', this.colors[index % this.colors.length]);
            path.setAttribute('stroke', '#ffffff');
            path.setAttribute('stroke-width', '1');
            path.style.cursor = 'pointer';
            
            svg.appendChild(path);
            
            // 添加文字
            const textAngle = startAngle + sectionAngle / 2;
            const textRadius = radius * 0.7;
            const textX = centerX + textRadius * Math.cos((textAngle * Math.PI) / 180);
            const textY = centerY + textRadius * Math.sin((textAngle * Math.PI) / 180);
            
            const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
            text.setAttribute('x', textX);
            text.setAttribute('y', textY);
            text.setAttribute('text-anchor', 'middle');
            text.setAttribute('dominant-baseline', 'middle');
            text.setAttribute('fill', 'white');
            text.setAttribute('font-size', '12');
            text.setAttribute('font-weight', '500');
            text.setAttribute('transform', `rotate(${textAngle}, ${textX}, ${textY})`);
            text.style.textShadow = '1px 1px 2px rgba(0,0,0,0.5)';
            text.style.pointerEvents = 'none';
            text.textContent = food;
            
            svg.appendChild(text);
        });
        
        this.wheel.appendChild(svg);
    }
    
    // 创建默认菜品标签
    createDefaultFoodTags() {
        this.defaultFoodsContainer.innerHTML = '';
        
        this.defaultFoods.forEach(food => {
            const tag = document.createElement('button');
            tag.className = 'food-tag';
            tag.textContent = food;
            tag.dataset.food = food;
            
            // 检查是否已选中
            if (this.currentFoods.includes(food)) {
                tag.classList.add('selected');
            }
            
            tag.addEventListener('click', () => this.toggleFood(food, tag));
            this.defaultFoodsContainer.appendChild(tag);
        });
    }
    
    // 切换菜品选择
    toggleFood(food, tag) {
        if (this.currentFoods.includes(food)) {
            // 移除菜品
            this.currentFoods = this.currentFoods.filter(f => f !== food);
            tag.classList.remove('selected');
        } else {
            // 添加菜品
            this.currentFoods.push(food);
            tag.classList.add('selected');
        }
        
        // 确保至少有一个菜品
        if (this.currentFoods.length === 0) {
            this.currentFoods.push(food);
            tag.classList.add('selected');
            this.showMessage('至少要选择一个菜品哦～', 'warning');
            return;
        }
        
        this.createWheel();
    }
    
    // 添加自定义菜品
    addCustomFood() {
        const customFood = this.customFoodInput.value.trim();
        
        if (!customFood) {
            this.showMessage('请输入菜品名称～', 'warning');
            return;
        }
        
        if (customFood.length > 10) {
            this.showMessage('菜品名称太长啦，请控制在10个字符内～', 'warning');
            return;
        }
        
        if (this.currentFoods.includes(customFood)) {
            this.showMessage('这个菜品已经存在啦～', 'warning');
            return;
        }
        
        // 添加emoji前缀
        const foodWithEmoji = customFood.includes('�') ? customFood : `🍽️ ${customFood}`;
        this.currentFoods.push(foodWithEmoji);
        this.createWheel();
        this.customFoodInput.value = '';
        
        this.showMessage('添加成功！', 'success');
    }
    
    // 开始抽奖
    spin() {
        if (this.isSpinning) return;
        
        if (this.currentFoods.length === 0) {
            this.showMessage('请先选择一些菜品～', 'warning');
            return;
        }
        
        this.isSpinning = true;
        this.spinBtn.disabled = true;
        this.spinBtn.querySelector('.btn-text').textContent = '抽奖中...';
        this.resultSection.classList.remove('show');
        
        // 计算随机角度
        const randomIndex = Math.floor(Math.random() * this.currentFoods.length);
        const sectionAngle = 360 / this.currentFoods.length;
        const targetAngle = randomIndex * sectionAngle;
        
        // 多转几圈增加效果
        const spins = 5 + Math.random() * 5;
        const finalRotation = this.currentRotation + (spins * 360) + (360 - targetAngle);
        
        // 应用旋转动画
        this.wheel.style.transform = `rotate(${finalRotation}deg)`;
        this.currentRotation = finalRotation % 360;
        
        // 动画结束后显示结果
        setTimeout(() => {
            this.showResult(this.currentFoods[randomIndex]);
            this.isSpinning = false;
            this.spinBtn.disabled = false;
            this.spinBtn.querySelector('.btn-text').textContent = '再来一次';
        }, 3000);
    }
    
    // 显示结果
    showResult(selectedFood) {
        const now = new Date();
        const timeString = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
        
        this.resultFood.textContent = selectedFood;
        this.resultTime.textContent = `抽奖时间：${timeString}`;
        this.resultSection.classList.add('show');
        
        // 保存到本地存储
        this.saveResult(selectedFood, timeString);
        
        // 播放庆祝动画
        this.celebrateAnimation();
    }
    
    // 庆祝动画
    celebrateAnimation() {
        // 创建飘落的emoji
        const emojis = ['🎉', '🎊', '✨', '🌟', '💖', '🎈'];
        
        for (let i = 0; i < 15; i++) {
            setTimeout(() => {
                const emoji = document.createElement('div');
                emoji.textContent = emojis[Math.floor(Math.random() * emojis.length)];
                emoji.style.cssText = `
                    position: fixed;
                    top: -50px;
                    left: ${Math.random() * 100}vw;
                    font-size: ${20 + Math.random() * 20}px;
                    z-index: 1000;
                    pointer-events: none;
                    animation: fall 3s linear forwards;
                `;
                
                document.body.appendChild(emoji);
                
                setTimeout(() => {
                    emoji.remove();
                }, 3000);
            }, i * 100);
        }
        
        // 添加掉落动画CSS
        if (!document.getElementById('celebration-styles')) {
            const style = document.createElement('style');
            style.id = 'celebration-styles';
            style.textContent = `
                @keyframes fall {
                    to {
                        transform: translateY(100vh) rotate(360deg);
                        opacity: 0;
                    }
                }
            `;
            document.head.appendChild(style);
        }
    }
    
    // 保存结果到本地存储
    saveResult(food, time) {
        const result = { food, time };
        localStorage.setItem('lastFoodLottery', JSON.stringify(result));
        this.updateLastResult(result);
    }
    
    // 加载上次结果
    loadLastResult() {
        const lastResult = localStorage.getItem('lastFoodLottery');
        if (lastResult) {
            const result = JSON.parse(lastResult);
            this.updateLastResult(result);
        }
    }
    
    // 更新上次结果显示
    updateLastResult(result) {
        this.lastResult.innerHTML = `
            <p><strong>${result.food}</strong></p>
            <p style="font-size: 0.8rem; opacity: 0.7; margin-top: 5px;">${result.time}</p>
        `;
    }
    
    // 显示消息提示
    showMessage(message, type = 'info') {
        // 移除已存在的消息
        const existingMessage = document.querySelector('.message-toast');
        if (existingMessage) {
            existingMessage.remove();
        }
        
        const toast = document.createElement('div');
        toast.className = `message-toast ${type}`;
        toast.textContent = message;
        toast.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: ${type === 'success' ? '#d4edda' : type === 'warning' ? '#fff3cd' : '#d1ecf1'};
            color: ${type === 'success' ? '#155724' : type === 'warning' ? '#856404' : '#0c5460'};
            padding: 12px 20px;
            border-radius: 25px;
            font-size: 0.9rem;
            font-weight: 500;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            animation: slideInDown 0.3s ease-out;
        `;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.style.animation = 'slideOutUp 0.3s ease-out forwards';
            setTimeout(() => toast.remove(), 300);
        }, 2000);
        
        // 添加动画CSS
        if (!document.getElementById('toast-styles')) {
            const style = document.createElement('style');
            style.id = 'toast-styles';
            style.textContent = `
                @keyframes slideInDown {
                    from {
                        opacity: 0;
                        transform: translateX(-50%) translateY(-20px);
                    }
                    to {
                        opacity: 1;
                        transform: translateX(-50%) translateY(0);
                    }
                }
                @keyframes slideOutUp {
                    from {
                        opacity: 1;
                        transform: translateX(-50%) translateY(0);
                    }
                    to {
                        opacity: 0;
                        transform: translateX(-50%) translateY(-20px);
                    }
                }
            `;
            document.head.appendChild(style);
        }
    }
    
    // 绑定事件
    bindEvents() {
        this.spinBtn.addEventListener('click', () => this.spin());
        this.addFoodBtn.addEventListener('click', () => this.addCustomFood());
        
        this.customFoodInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addCustomFood();
            }
        });
        
        // 防止输入过长
        this.customFoodInput.addEventListener('input', (e) => {
            if (e.target.value.length > 10) {
                e.target.value = e.target.value.slice(0, 10);
                this.showMessage('菜品名称最多10个字符哦～', 'warning');
            }
        });
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new FoodLottery();
});

// 添加一些可爱的交互效果
document.addEventListener('DOMContentLoaded', () => {
    // 点击效果
    document.addEventListener('click', (e) => {
        if (e.target.matches('button, .food-tag')) {
            const ripple = document.createElement('div');
            const rect = e.target.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = e.clientX - rect.left - size / 2;
            const y = e.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                background: rgba(255, 255, 255, 0.5);
                border-radius: 50%;
                transform: scale(0);
                animation: ripple 0.6s linear;
                pointer-events: none;
            `;
            
            e.target.style.position = 'relative';
            e.target.style.overflow = 'hidden';
            e.target.appendChild(ripple);
            
            setTimeout(() => ripple.remove(), 600);
        }
    });
    
    // 添加涟漪动画CSS
    if (!document.getElementById('ripple-styles')) {
        const style = document.createElement('style');
        style.id = 'ripple-styles';
        style.textContent = `
            @keyframes ripple {
                to {
                    transform: scale(2);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(style);
    }
});